<template>
	<view>
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :multiple="multiple" :width="width" :height="height"
			:maxCount="maxCount" :disabled="disabled"></u-upload>
	</view>
</template>

<script>
	import * as API from '@/common/api';
	import store from '@/store'
    import config from '@/common/config'
	export default {
		props: {
			ossIds: {
				type: String,
				default: ''
			},
			disabled:{
				type: Boolean,
				default: false
			},
			multiple: {
				type: Boolean,
				default: true
			},
			maxCount: {
				type: Number,
				default: 10
			},
			width: {
				type: Number,
				default: 80
			},
			height: {
				type: Number,
				default: 80
			},
		},
		data() {
			return {
				fileList: []
			}
		},
		methods: {
			async initFileList() {
				if (this.ossIds) {
					const res = await API.getFileList(this.ossIds);
					if(this.maxCount==1)
					{
						this.fileList=[{
							status: 'success',
							message: '',
							url: res.data[0].url,
							ossId: res.data[0].ossId
						}]
					}
					else
					{
						this.fileList = res.data.map(item => {
							return {
								status: 'success',
								message: '',
								url: item.url,
								ossId: item.ossId
							}
							
						})
					}
					
				}
			},
			async deletePic(event) {
				const res = await API.removeFile(event.file.ossId);
				this.fileList.splice(event.index, 1);

			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url,
						ossId: result.ossId

					}))
					fileListLen++
				}
				const tempOssIds = this.fileList.map(item => item.ossId).join(',');
				this.$emit('update:ossIds', tempOssIds);
			},
			uploadFilePromise(tempUrl) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$config.baseUrl + 'resource/oss/upload',
						filePath: tempUrl,
						name: 'file',
						header: {
							// Authorization: 'Bearer ' + store.getters.token,
							Authorization: 'Bearer ' + uni.getStorageSync('token'),
							clientid : config.clientId,
						},
						success: (res) => {
							const data = res.data ? JSON.parse(res.data) : {};
							resolve(data.data)
						},
						fail: (err) => {
							console.log("得到上传的错误",err);
							reject(err);
						}
					});
				});
			}
		},
		watch: {
			ossIds: {
				handler(newVal) {
					this.initFileList();
				},
				immediate: true,
			},
		},
	}
</script>
